<template>
  <div class="home-container">
    <el-container>
      <el-header class="app-header">
        <h2>医疗信息管理系统</h2>
      </el-header>
      <el-container class="main-container">
        <el-container class="content-container">
          <el-col :span="6">
          <div class="left-aside">
            <LeftMenu ref="leftMenuRef" />
          </div>
          </el-col>
          <el-col :span="10">
          <div class="middle-main">
            <MiddleOptions ref="middleOptionsRef" @form-data-change="handleFormDataChange" @card-removed="handleCardRemoved" />
          </div>
          </el-col>
          <el-col :span="8">
          <div class="right-aside">
            <RightInfo ref="rightInfoRef" @option-changed="handleOptionChanged" />
          </div>
          </el-col>
        </el-container>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import LeftMenu from '@/components/LeftMenu.vue'
import MiddleOptions from '@/components/MiddleOptions.vue'
import RightInfo from '@/components/RightInfo.vue'
import { useMedicalStore } from '@/store/medical'

const store = useMedicalStore()
const leftMenuRef = ref(null)
const middleOptionsRef = ref(null)
const rightInfoRef = ref(null)

// 生成检查所见文本的函数
const generateObservationText = (selectedLeafNodes) => {
  if (!selectedLeafNodes || selectedLeafNodes.length === 0) {
    return ''
  }

  const textParts = []

  selectedLeafNodes.forEach(node => {
    if (!node.formData || !node.detail) return

    // 添加卡片名称（黑体）
    textParts.push(`**${node.name}**：`)

    const itemTexts = []
    
    node.detail.forEach(formItem => {
      const itemId = formItem.id
      const itemName = formItem.name
      
      switch (formItem.type) {
        case 0: // 输入框
          const inputValue = node.formData[`item_${itemId}_input`]
          if (inputValue && inputValue.trim()) {
            itemTexts.push(`${itemName}：${inputValue}`)
          }
          break
          
        case 1: // 单选
          const radioValue = node.formData[`item_${itemId}_radio`]
          
          if (radioValue) {
            try {
              // 使用base64编码存储选项数据，避免HTML属性长度限制和特殊字符问题
              const optionsJson = JSON.stringify(formItem.organScheme?.options || [])
              const encodedOptions = btoa(encodeURIComponent(optionsJson))
              // 增加 data-node-id，便于右侧更新时只影响对应卡片
              itemTexts.push(`${itemName}：<span class="clickable-option" data-item-id="${itemId}" data-node-id="${node.id}" data-options-encoded="${encodedOptions}">${radioValue}</span>`)
            } catch (error) {
              console.error('❌ Error generating clickable option for:', itemName, error)
              // 降级处理：不生成可点击选项
              itemTexts.push(`${itemName}：${radioValue}`)
            }
          }
          break
          
        case 2: // 多选
          const checkboxValues = node.formData[`item_${itemId}_checkbox`]
          if (checkboxValues && checkboxValues.length > 0) {
            itemTexts.push(`${itemName}：${checkboxValues.join('、')}`)
          }
          break
          
        case 3: // 输入框带单位
          const inputWithUnitValue = node.formData[`item_${itemId}_input`]
          const unitValue = node.formData[`item_${itemId}_unit`]
          if (inputWithUnitValue && inputWithUnitValue.trim()) {
            itemTexts.push(`${itemName}：${inputWithUnitValue}${unitValue || ''}`)
          }
          break
          
        case 4: // 面积计算
          const length = node.formData[`item_${itemId}_length`]
          const width = node.formData[`item_${itemId}_width`]
          const areaUnit = node.formData[`item_${itemId}_unit`]
          if (length && width) {
            const area = (parseFloat(length) * parseFloat(width)).toFixed(2)
            itemTexts.push(`${itemName}：${length}×${width}=${area}${areaUnit || ''}`)
          }
          break
          
        case 5: // 体积计算
          const vLength = node.formData[`item_${itemId}_length`]
          const vWidth = node.formData[`item_${itemId}_width`]
          const height = node.formData[`item_${itemId}_height`]
          const volumeUnit = node.formData[`item_${itemId}_unit`]
          if (vLength && vWidth && height) {
            const volume = (parseFloat(vLength) * parseFloat(vWidth) * parseFloat(height)).toFixed(2)
            itemTexts.push(`${itemName}：${vLength}×${vWidth}×${height}=${volume}${volumeUnit || ''}`)
          }
          break
      }
    })
    
    if (itemTexts.length > 0) {
      textParts.push(itemTexts.join('；'))
    }
    
    textParts.push('') // 添加空行分隔不同卡片
  })

  return textParts.join('\n').trim()
}

// 监听选中的叶子节点变化
watch(
  () => store.selectedLeafNodes,
  (newNodes) => {
    const observationText = generateObservationText(newNodes)
    if (rightInfoRef.value) {
      rightInfoRef.value.updateObservation(observationText)
    }
  },
  { deep: true, immediate: true }
)

// 处理表单数据变化
const handleFormDataChange = () => {
  const observationText = generateObservationText(store.selectedLeafNodes)
  if (rightInfoRef.value) {
    rightInfoRef.value.updateObservation(observationText)
  }
}

// 处理卡片移除事件
const handleCardRemoved = ({ nodeId, organId }) => {
  // 通知左侧菜单取消勾选对应的叶子节点
  if (leftMenuRef.value) {
    leftMenuRef.value.uncheckLeafNode(nodeId, organId)
  }
}

// 处理右侧下拉框选项变化
const handleOptionChanged = ({ itemId, nodeId, newValue }) => {
  try {
    // 统一使用字符串进行匹配和作为表单键的一部分，避免数字/字符串类型不一致导致匹配失败
    const idStr = String(itemId)
    const targetNodeIdStr = nodeId != null ? String(nodeId) : null

    store.selectedLeafNodes.forEach(node => {
      // 若提供了 nodeId，则仅更新目标卡片
      if (targetNodeIdStr && String(node.id) !== targetNodeIdStr) return

      // 检查节点的详情中是否包含对应的表单项（用字符串比较确保稳健）
      if (node.detail && node.detail.some(formItem => String(formItem.id) === idStr)) {
        if (node.formData) {
          const fieldKey = `item_${idStr}_radio`
          const prev = node.formData[fieldKey]
          node.formData[fieldKey] = newValue

          console.log('[handleOptionChanged] itemId(raw):', itemId, '=> idStr:', idStr, 'nodeId:', nodeId)
          console.log('[handleOptionChanged] fieldKey:', fieldKey, 'prev:', prev, 'next:', newValue)

          // 重新生成观察文本以反映变化
          nextTick(() => {
            const observationText = generateObservationText(store.selectedLeafNodes)
            if (rightInfoRef.value) {
              rightInfoRef.value.updateObservation(observationText)
            }
          })
        }
      }
    })
  } catch (error) {
    console.error('Error in handleOptionChanged:', error)
  }
}
</script>

<style scoped>
.home-container {
  height: 100vh;
  width: 100%;
}

.app-header {
  background-color: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  padding: 0 20px;
  height: 60px !important;
}

.main-container {
  height: calc(100vh - 60px);
}

.content-container {
  display: flex;
  width: 100%;
  height: 100%;
}

.left-aside, .middle-main, .right-aside {
  flex: 1;
  height: 100%;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
}

.left-aside {
  background-color: #f5f7fa;
}

.middle-main {
  background-color: #fff;
}

.right-aside {
  background-color: #f5f7fa;
}
</style>